/*
 * @Description: 用户仓库组件
 * @Author: fhw
 * @Date: 2021-04-17 14:10
 */
import { defineComponent, PropType, computed, onMounted } from 'vue'
import { Options, UserDataModule } from '@/store/modules/user'
import { isEmpty } from 'ramda'
import { Select } from 'ant-design-vue'
import { filterOptionCaseInsensitive } from '@/utils'
import { isArray } from '@/utils/tools'
type propKey = 'roleList' | 'homeUserList'

const Props = {
	value: [String, Number, Array] as PropType<string | number | any[]>,
	label: [String, Number, Array] as PropType<string | number | any[]>,
	disabled: {
		type: Boolean as PropType<boolean>,
		default: false,
	},
	prop: {
		type: String as PropType<propKey>,
		default: 'sysUserList',
		required: true,
	},
	mode: String as PropType<'multiple' | 'tags' | 'SECRET_COMBOBOX_MODE_DO_NOT_USE'>,
	placeholder: String as PropType<string>,
	allowClear: {
		type: Boolean as PropType<boolean>,
		default: true,
	},
	filter: {
		type: Function as PropType<(item: Options) => boolean>,
	},
	showSearch: {
		type: Boolean as PropType<boolean>,
		default: true,
	},
	onChange: Function as PropType<(item: ObjectMap) => void>,
}
const FormUserData = defineComponent({
	name: 'form-userData',
	props: Props,
	setup(props, { emit }) {
		const computeCount = computed(() => {
			const filter = props.filter
			if (filter) {
				return (UserDataModule[props.prop] as Options[]).filter(filter)
			} else {
				return UserDataModule[props.prop]
			}
		})
		function onChange(value: number | Array<string>, option?: Options | Options[]) {
			if (isArray(value)) {
				if (option && isArray(option)) {
					emit(
						'update:label',
						option.map((item: Options) => {
							return item.label
						})
					)
				} else {
					emit('update:label', undefined)
				}
				if (value.length) {
					emit('update:value', value)
				} else {
					emit('update:value', undefined)
				}
			} else {
				if (option && !isArray(option)) {
					emit('update:value', (option as Options).value)
					emit('update:label', (option as Options).label)
				} else {
					emit('update:value', undefined)
					emit('update:label', undefined)
				}
			}
			if (props.onChange) {
				props.onChange({ value: value, option: option })
			}
		}
		onMounted(() => {
			if (isEmpty(UserDataModule[props.prop])) {
				const Action = ('get' + props.prop.slice(0, 1).toUpperCase() + props.prop.slice(1)) as 'getRoleList'
				UserDataModule[Action]()
			}
		})

		return () => (
			<Select
				onChange={onChange}
				mode={props.mode}
				disabled={props.disabled}
				allowClear={props.allowClear}
				value={props.value}
				placeholder={props.placeholder}
				options={computeCount.value}
				showSearch={props.showSearch}
				filterOption={filterOptionCaseInsensitive}
			/>
		)
	},
})

export default FormUserData
